/*
    31. Write a program in C to split string by space into words. 
    Test Data :
    Input a string : this is a test string
    Expected Output :

    Strings or words after split by space are : 

    this
    is 
    a 
    test 
    string .
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#define MAX_LEN 1024
#define MAX_STR 256

char *strs[MAX_STR];

char* getstr(char *str)
{
    char ch;
    char *p = str;
    while((ch = getchar()) != '\n'){
        *p++ = ch;
    }
    *p = '\0';
    return str;
}

void getword(char *str)
{
    int i = 0;
    int len = 0;
    char *p;
    while(1){
        if(isalpha(*str)){
            len++;
        }else if(len){            
            p = malloc(len + 1);
            strncpy(p, str - len, len);
            *(p + len) = '\0';
            strs[i++] = p;
            len = 0;
        }
        if(*str == '\0') 
            break;
        str++;
    }
    strs[i] = NULL;
}

void printstr(char *s[])
{
    int i = 0;
    while(s[i] != NULL){
        printf("%s\n", s[i]);
        i++;
    }
}

int main(void)
{
    char *str = malloc(MAX_LEN);
    printf("Input a string : ");
    getstr(str);
    getword(str);
    printf("Strings or words after split by space are :\n");
    printstr(strs);

    return 0;
}